# -*- coding: utf-8 -*-

import cgi, sys, os
import datetime,logging

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db

from gaesessions import get_current_session
from db import Mp, Thread
import s


class send(webapp.RequestHandler):
  def post(self):
	"""envoie un message en tant que app"""
	try:
		app = self.request.get('app')
		mdp = self.request.get('mdp')
		msg = self.request.get('msg')
		suj = self.request.get('suj')
		to  = self.request.get('to')
		if mdp != s.app[app]:
			self.response.out.write('%s %s'%(mdp, s.app[app]))
			return
		if msg == '':
			self.response.out.write('pas de message')
			self.error(412)
			return 
		if to == '':
			self.response.out.write('pas de destinataire')
			self.error(412)
			return

		mTo = to.split(';')
		for t in mTo:

			message = Mp()
			message.author = app
			message.destin = t
			message.subject = suj
			message.message = msg
			message.state = 0
			message.secure = True
			msgInDb = message.put()

			thread = Thread()
			thread.author = app
			thread.destin = t
			thread.subject = suj
			thread.msgs = [msgInDb]
			thread.last = datetime.datetime.today()
			thread.stateIn = 0
			thread.stateOut = 1
			thread.put()

		self.response.out.write('ok')
		return

	except:
		self.response.out.write('une erreur est survenue : %s'%sys.exc_info()[1])
		return


class dummy(webapp.RequestHandler):
	def post(self):
		self.response.out.write('ok')
